package payment

import (
	"fmt"
	"github.com/gofiber/fiber/v2"
	"sg-backend/global"
	"sg-backend/model/paylog"
	"time"
)

/*
 * method  GET
 * path    /api/paymentLog
 */

// 处理回传前端的数据结构
type _PaymentDataJson struct {
	Id         uint       `json:"id"`
	PayType    any        `json:"payType"`
	Money      float64    `json:"money"`
	FamilyType any        `json:"familyType"`
	Time       *time.Time `json:"time"`
	Refund     float64    `json:"refund"`
	RefundTime *time.Time `json:"refundTime"`
	Date       string     `json:"date"`
	Remark     string     `json:"remark"`
}

type _JsonType struct {
	TypeList []string `json:"typeList"`
}

// GetPaymentLog GET请求，获取数据
func GetPaymentLog(ctx *fiber.Ctx) error {

	// 计算分页，mysql第一页为0计算
	pageSize := ctx.QueryInt("pageSize", 10)
	current := ctx.QueryInt("current", 1)
	offSet := (current - 1) * pageSize

	// 按支出分类检索
	typeId := ctx.QueryInt("type")
	var typeList []uint
	if typeId > 0 {
		typeList = append(typeList, uint(typeId))
	} else {

		// 按全部支出分类检索
		var payTypeList []paylog.PayType
		if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).Find(&payTypeList); err.Error != nil {
			return ctx.JSON(fiber.Map{
				"status":  "error",
				"message": "解构支出类型List失败！！",
			})
		}
		for _, v := range payTypeList {
			typeList = append(typeList, v.Id)
		}
	}

	// 按对象检索
	familyId := ctx.QueryInt("family")
	var familyList []uint
	if familyId > 0 {
		familyList = append(familyList, uint(familyId))
	} else {

		// 按全部对象检索
		var familyTypeList []paylog.FamilyType
		if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).Find(&familyTypeList); err.Error != nil {
			return ctx.JSON(fiber.Map{
				"status":  "error",
				"message": "获取家庭成员List失败！！",
			})
		}
		for _, v := range familyTypeList {
			familyList = append(familyList, v.Id)
		}
	}

	// 总数
	var total int64

	// 指定数据model
	var payLogs []paylog.PayLog

	// 匹配全部数据，计算总数
	r := global.DB.Preload("PayType").Preload("FamilyType").Where("user_id = ?", global.AuthUser.UserId).
		Where("pay_type_id IN ? AND family_type_id IN ?", typeList, familyList).
		Model(&paylog.PayLog{}).Count(&total)
	if r.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "数据库查询出错！" + r.Error.Error(),
		})
	}
	if r.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "数据库查询出错！" + r.Error.Error(),
		})
	}

	// 2，分页处理
	if err := r.Order("time desc").Offset(offSet).Limit(pageSize).Find(&payLogs); err.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "数据分页出错！" + err.Error.Error(),
		})
	}

	// 3，对查询到的数据进行处理，将同日期的删除
	var checkDate = ""
	var data []_PaymentDataJson
	for _, v := range payLogs {
		// 日期检测
		fmt.Printf("%+v", v)
		_date := v.Time.Format("2006-01-02")
		if checkDate == _date {
			_date = ""
		} else {
			// 日期不相等，是新的一天
			checkDate = v.Time.Format("2006-01-02")
		}
		data = append(data, _PaymentDataJson{
			Id:         v.Id,
			PayType:    v.PayType,
			Money:      v.Money,
			FamilyType: v.FamilyType,
			Time:       v.Time,
			Date:       _date,
			Remark:     v.Remark,
			Refund:     v.Refund,
			RefundTime: v.RefundTime,
		})
	}

	// 查询结束返回结果
	return ctx.JSON(fiber.Map{
		"status":   "done",
		"success":  true,
		"message":  "请求成功！",
		"data":     data,
		"total":    total,
		"current":  current,
		"pageSize": pageSize,
	})
}
